<template>
	<view class="">
		<!-- <view class="top-box">
			<view class="u-demo-block__content">
				<view class="input-search">
					<u-input placeholder="请输入商品标题" v-model="queryKey" border="none" clearable>
						<template slot="prefix">
							<u-icon name="search" color="#BCBDBD" size="28"></u-icon>
						</template>
						<template slot="suffix">
							<view class="search" @click="search">搜索</view>
						</template>
					</u-input>
				</view>
				<u-icon name="scan" color="#FFFFFF" size="32" style="margin-left: 10rpx;" @tap="startScan"></u-icon>
			</view>
		</view> -->
		<!-- 顶部 -->
		<view class="top-box">
			<view class="top-site">
				<view class="left-box" style="padding-left: 20rpx;">
					<view class="location" @click="location">
						<uni-icons type="location" size="16"></uni-icons>
						<view>
							<text class="city">{{city}}市</text>
							<uni-icons type="down" size="12" style="margin: 0 4rpx;"></uni-icons>
						</view>
						<text class="temperature">{{temperature}}°c</text>
						<text class="weather">｜{{weatherInfo}}</text>
					</view>
				</view>
				<view class="banner-box">
					<view v-for="(item, index) in bannerList" :key="index" class="banner-item"
						:class="{active: currentIndex === index}">
						<image :src="item.imageUrl" mode="aspectFill" class="banner-img"></image>
					</view>
				</view>

			</view>
			<view class="input-box">
				<view class="input-item">
					<uni-easyinput primaryColor="#fff" style="color:#000" :placeholderStyle="placeholderStyle"
						placeholder="请输入店铺名称或商品名称" :inputBorder="false" v-model="queryKey" @confirm='search'>
						<template #left>
							<uni-icons type="scan" size="26" color="#FE0F23" style="margin-left: 20rpx;"></uni-icons>
						</template>
						<template #right>
							<div class="rightBtn" @tap='search'>搜索</div>
						</template>
					</uni-easyinput>
				</view>
			</view>
			<view class="tab-bar">
				<view class="tab-scroll">
					<view class="tab-item" v-for="(item, index) in categories" :key="index" @tap="onTabTap(index,item)">
						<text :class="index === activeIndex ? 'active' : ''">{{ item.categoryName }}</text>
						<view v-if="index === activeIndex" class="tab-border"></view>
					</view>
				</view>
			</view>
			<!-- 滑块列表 -->
			<view class="carousel-box">
				<u-scroll-list indicatorActiveColor="#FA2E2C">
					<view v-for="(item, index) in tabList" :key="index" class="carousel-item" @click="goUrl(item)">
						<image :src="item.iconUrl" mode=""></image>
						<text>{{item.categoryName}}</text>
					</view>
				</u-scroll-list>
			</view>
		</view>
		<!-- 中间内容 -->
		<view class="content">
			<view class="left-item">
				<view class="title">经销商频道</view>
				<view class="min-title">好物购不停</view>
				<view class="examine" @click='changeOperationItem({type:2})'>立即查看</view>
			</view>
			<view class="right-item">
				<view class="item i1" @click='changeOperationItem({type:1})'>
					<view class="title">供货商频道</view>
					<view class="min-title">优惠购好物</view>
				</view>
				<view class="item i2" @click='changeOperationItem({type:3})'>
					<view class="title">多多优选</view>
					<view class="min-title">大宗商品交易所</view>
				</view>
			</view>
		</view>
		<!-- 列表 -->
		<view class='hotGoods'>
			<!-- <view class="top-title-img">
				<image src="/static/index/baifenbi.png" mode="" class="img1"></image>
				<image src="/static/index/hwtj.png" mode="" class="img2"></image>
			</view> -->
			<view :class="['list-content']">
				<goods-item :dates="item" v-for="item in vipList" :key="item.id" @callBack='handleToDetails' />
			</view>
		</view>
	</view>
</template>

<script>
	import {
		appVersionInfo,
		bannerList,
		nearestTime,
		myVoucherGoodsPage,
		buyMemberGoods,
		getNoticeList,
		personalData,
		getWeatherAndCity,
		getIndexCategoryList
	} from '../../api/api.js'
	import {
		getTransferToTxUserNameAvatar
	} from "@/api/api.js"
	import scrollList from "../../components/scroll-list/scroll-list.vue"
	import JingangDistrict from "@/components/basicComponents/JingangDistrict.vue"
	import goodsItem from "@/components/basicComponents/goodsItem.vue"
	export default {
		data() {
			return {
				city: '',
				temperature: '',
				weatherInfo: '',
				queryKey: '',
				placeholderStyle: "color:#898E92;font-size:28rpx;",
				userInfo: {},
				bannerList: [],
				currentIndex: 0,
				previousMargin: '15px',
				nextMargin: '15px',
				list: [], // 商品列表
				state: '', // 状态0还未到1进行中2已过期
				time: '', // 倒计时
				interval: '',
				appInfo: '',
				timestamp: '',
				vipData: {},
				memberLevel: uni.getStorageSync('memberLevel'),
				noticeInfo: [],
				downloading: false,
				pageSize: 20,
				pageNum: 1,
				pages: '',
				vipList: [],
				scrollLeft: 0, // 控制滚动位置
				type: 1,
				showPopup: true,
				activeIndex: 0,
				categories: [{
						categoryName: '全部'
					},
					{
						categoryName: '食品生鲜'
					},
					{
						categoryName: '家用电器'
					},
					{
						categoryName: '家具百货'
					},
					{
						categoryName: '美妆个护'
					}
				],
				tabList: [{
					iconUrl: '/static/ddsh.png',
					categoryName: '水果生鲜'
				}, {
					iconUrl: '/static/ddsh.png',
					categoryName: '休闲食品'
				}, {
					iconUrl: '/static/ddsh.png',
					categoryName: '饮料饮品'
				}, {
					iconUrl: '/static/ddsh.png',
					categoryName: '粮油米面'
				}, {
					iconUrl: '/static/ddsh.png',
					categoryName: '日用百货'
				}, {
					iconUrl: '/static/ddsh.png',
					categoryName: '日用洗护'
				}]
			}
		},
		components: {
			JingangDistrict,
			// scrollList,
			goodsItem,

		},
		onReachBottom() {
			if (this.pages <= this.pageNum) {
				uni.showToast({
					icon: 'none',
					title: '暂无更多~'
				})
				return
			} else {
				this.pageNum++
				this.getMemberGoodsList()
			}

		},
		onPullDownRefresh() {
			this.pageNum = 1
			this.getMemberGoodsList()
		},
		onShow() {
			this.getWeatherAndCity();
			this.getIndexCategoryList();
			this.personalData();
			this.getNoticeLists()
			// 获取首页-轮播图
			this.getBanner()
			// 获取首页推荐商品列表
			// this.getRecommend()
			// 获取会员礼包列表
			this.getMemberGoodsList(1)
			//#ifdef APP-PLUS
			// 获取app版本信息
			this.getAppVersionInfo()
			//#endif
			clearInterval(this.interval)
		},
		onHide() {
			this.navList = []
		},
		onUnload() {
			clearInterval(this.interval)
		},
		onHide() {
			// 清除所有计时器
			clearInterval(this.interval)
		},
		onLoad() {
			setTimeout(() => {
				this.$refs.popup.open('center')
			}, 100)
		},
		methods: {
			search() {
				this.pageNum = 1;
				this.getMemberGoodsList();
			},
			goUrl(item) {
				uni.showToast({
					icon: 'none',
					title: '敬请期待！'
				})
			},
			//顶部点击切换
			onTabTap(index, item) {
				// this.activeIndex = index;
				uni.showToast({
					icon: 'none',
					title: '敬请期待！'
				})
			},
			getIndexCategoryList() {
				let data = {}
				getIndexCategoryList(data).then(res => {
					this.tabList = res.data || []
				})
			},
			getWeatherAndCity() {
				getWeatherAndCity().then(res => {
					if (res.code === 200) {
						this.city = res.data.city;
						this.temperature = res.data.temperature;
						this.weatherInfo = res.data.weatherInfo;
					}
				})
			},
			liveStreaming() {
				// this.userInfo.UserId
				// this.userInfo.userName
				// webUrl:"https://live-h5.huopeng.cc?userId=6666&nickName=你好"
				const id = this.userInfo.UserId
				const name = this.userInfo.userName
				// uni.navigateTo({
				// 	url: `./liveStreaming?userId=${id}&nickName=${name}`
				// })
				uni.switchTab({
					url: `./liveStreaming?userId=${id}&nickName=${name}`
				})
			},
			closePupop() {
				this.$refs.popup.close()
			},
			// scrollToCenter(index) {
			// 	this.selectedIndex = index;
			// 	const query = uni.createSelectorQuery().in(this);
			// 	query.select(`#tab-${index}`).boundingClientRect(res => {
			// 		if (res) {
			// 			const itemWidth = res.width;
			// 			const itemLeft = res.left;
			// 			const containerWidth = this.$el.querySelector('.container').clientWidth;
			// 			const scrollLeft = itemLeft - (containerWidth / 2) + (itemWidth / 2);

			// 			// 更新 scrollLeft，触发滚动
			// 			this.scrollLeft = scrollLeft;
			// 		}
			// 	}).exec();
			startScan() {
				uni.scanCode({
					onlyFromCamera: true, // 只允许从相机扫码
					success: (res) => {
						const str = res.result;
						console.log(res);
						const parts = str.split('-', 2); // 限制分割次数为 2
						const beforeDash = parts[0]; // 分割前的部分
						const afterDash = parts[1]; // 分割后的部分
						if (beforeDash == 'txh') {
							console.log('多多生活不可扫描多多生活')
							uni.showToast({
								icon: 'none',
								title: '扫描失败！'
							})
							return
						}
						if (beforeDash == 'tx') {
							this.handleScanResult(str);
							return
						}
						if (beforeDash != 'kllz' && beforeDash != 'tx' && beforeDash != 'txh') {
							uni.showToast({
								icon: 'none',
								title: '扫描失败，请重新尝试'
							})
							return
						}
						console.log('分割前的部分:', beforeDash); // 输出: tx
						console.log('分割后的部分:', afterDash); // 输出: GGATmJ4gfEr+r6+
						// this.handleScanResult(res.result);
					},
					fail: (err) => {
						console.log(err);
						return
					}
				});
			},
			handleScanResult(scanData) {
				getTransferToTxUserNameAvatar({
					qrCode: scanData
				}).then(res => {
					if (res.code == 200) {
						uni.navigateTo({
							url: `/pages/mine/paymentMerchant/paymentMerchant?data=${encodeURIComponent(scanData)}`
						})
					} else {
						return
					}
				})
				// 处理扫码结果
				// uni.navigateTo({
				// 	url: `/pages/mine/paymentContent?data=${encodeURIComponent(scanData)}`
				// })
			},
			onSwiperChange(e) {
				this.currentIndex = e.detail.current;
			},
			getNoticeLists() {
				let data = {}
				getNoticeList(data).then(res => {
					this.noticeInfo = res.data
				})
			},
			personalData() {
				let data = {}
				personalData(data).then(res => {
					this.userInfo = res.data
				})
			},
			// 比较app版本号方法
			compareVersion(version1, version2) {
				const parts1 = version1.split('.').map(Number);
				const parts2 = version2.split('.').map(Number);

				for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
					const num1 = parts1[i] || 0;
					const num2 = parts2[i] || 0;

					if (num1 > num2) return 1;
					if (num1 < num2) return -1;
				}
				return 0;
			},
			// 获取app版本信息
			getAppVersionInfo() {
				let data = {
					businessType: 0,
					type: 0
				}

				appVersionInfo(data).then(res => {
					this.appInfo = res.data
					console.log(this.appInfo);
					const _this = this
					plus.runtime.getProperty(plus.runtime.appid, function(inf) {
						var connectAddress = res.data.connectAddress
						console.log(connectAddress);
						if (_this.compareVersion(inf.version, res.data.versionNumber) <= -1) {
							uni.showModal({
								title: '版本发布更新',
								content: '发现新版本，请进行更新',
								confirmColor: '#007AFF',
								showCancel: false,
								confirmText: '更新',
								success: function(res) {
									uni.showLoading({
										title: '正在下载中，请稍后'
									});
									if (plus.networkinfo.getCurrentType() === plus.networkinfo
										.CONNECTION_NONE) {
										uni.hideLoading();
										uni.showToast({
											title: '网络未连接，请检查网络',
											icon: 'none'
										})
										return
									}
									var task = plus.downloader.createDownload(
										connectAddress, {}, (download, status) => {
											if (status === 200) {
												plus.runtime.install(plus.io
													.convertLocalFileSystemURL(download
														.filename), {
														force: true
													}, () => {
														uni.hideLoading();
														uni.showToast({
															title: '安装成功',
															mask: false,
															duration: 1000
														});
														setTimeout(() => {
															plus.runtime
																.restart()
														}, 1500)
													}, (error) => {
														uni.hideLoading();
														uni.showToast({
															title: '安装失败：' +
																error.message,
															mask: false
														})
														console.log(error.message);
													})
											} else {
												uni.hideLoading();
												uni.showToast({
													title: '下载失败',
													mask: false
												});
											}
										})
									task.addEventListener("statechanged", (download) => {
										if (download.state === 3) { // 下载中
											let progress = (download.downloadedSize /
												download.totalSize) * 100
											console.log(`下载进度: ${progress}%`)
										}
									})
									task.start()
								}.bind(function() {

								})
							})
						}
					})
				})
			},
			// 获取首页-轮播图
			getBanner() {
				let data = {}
				bannerList(data).then(res => {
					this.bannerList = res.data
				})
			},
			// 获取首页推荐商品列表
			getRecommend() {
				let data = {}
				nearestTime(data).then(res => {
					this.state = res.data.state
					this.list = res.data.goodsList
					var that = this
					that.interval = setInterval(function() {
						if (res.data.state == 0) {
							that.timestamp = res.data.nextBeginTimestamp
							that.time = that.countDown(res.data.nextBeginTimestamp)
						} else if (res.data.state == 1) {
							that.timestamp = res.data.endTimestamp
							that.time = that.countDown(res.data.endTimestamp)
						}
					}, 1000)
				})
			},

			// 获取会员礼包列表
			getMemberGoodsList() {
				let data = {
					type: 1, //提货区
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					queryKey: this.queryKey
				}
				myVoucherGoodsPage(data).then(res => {
					console.log(res.data)
					uni.stopPullDownRefresh()
					this.pages = res.data.pages
					let result = res.data.records || []
					if (this.pageNum == 1) {
						this.vipList = [...result]
					} else {
						this.vipList = [...this.vipList, ...result]
					}
				})
			},
			// 购买会员礼包
			handleToDetails(item) {
				uni.navigateTo({
					url: '/pages/goods/goodsDetail?id=' + item.id + '&navId=2' + '&source=goods'
				})
			},
			// goDetail(item) {
			// 	uni.navigateTo({
			// 		url:'/pages/index/goodsDetail?goodsId=' + item.goodsId + '&timestamp=' + this.timestamp
			// 	})
			// },
			// 选择金刚区选项
			changeOperationItem(item) {
				if (item.type == 3) {
					// uni.showToast({
					// 	title: '敬请期待～',
					// 	icon: 'none',
					// 	duration: 1000
					// });
					// #ifdef H5
					window.open("https://szsc.huamaohz.cn/dwz/1Pl8UQej")
					// #endif
					// #ifdef APP-PLUS
					uni.navigateTo({
						url: '/pages/duoduoOptimization/duoduoOptimization'
					})
					// #endif
					return
				}

				let _this = this;
				// 判断平台  
				if (item.type) {
					uni.navigateTo({
						url: '/pages/subpage/homeGoodsList/homeGoodsList?type=' + item.type
					})
					return
				}
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android') {
					plus.runtime.launchApplication({
							pname: 'com.taobao.taobao'
						},
						function(e) {
							console.log('Open system default browser failed: ' + e.message);
						}
					);
				} else if (plus.os.name == 'iOS') {
					plus.runtime.launchApplication({
						action: 'taobao://'
					}, function(e) {
						console.log('Open system default browser failed: ' + e.message);
					});
				}
				// #endif
			}
		}
	}
</script>

<style>
	page {
		background: #F6F6FA;
	}
</style>
<style lang="less" scope>
	// .top-box {
	// 	width: 100%;
	// 	height: 788rpx;
	// 	background-image: url('@/static/index/top-bkg.png');
	// 	background-repeat: no-repeat;
	// 	background-size: 100% 100%;
	// 	padding-top: 98rpx;
	// 	box-sizing: border-box;

	// 	.u-demo-block__content {
	// 		width: 100%;
	// 		display: flex;
	// 		align-items: center;
	// 		padding: 0 20rpx;
	// 		box-sizing: border-box;

	// 		.input-search {
	// 			width: 100%;
	// 			height: 68rpx;
	// 			display: flex;
	// 			align-items: center;
	// 			border-radius: 50rpx;
	// 			padding: 0 4rpx 0 10rpx;
	// 			background-color: #FFFFFF;

	// 			.search {
	// 				width: 120rpx;
	// 				height: 64rpx;
	// 				background: linear-gradient(266deg, #EB517D 0%, #ED7D67 100%);
	// 				border-radius: 102rpx 102rpx 102rpx 102rpx;
	// 				font-size: 28rpx;
	// 				color: #FFFFFF;
	// 				line-height: 64rpx;
	// 				text-align: center;
	// 			}
	// 		}
	// 	}
	// }
	.top-box {
		height: 520rpx;
		box-sizing: border-box;
		background-image: url('/static/index/top-bkg-index.png');
		background-repeat: no-repeat;
		background-size: 100% 100%;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 10;

		.top-site {
			width: 100%;
			height: 176rpx;
			display: flex;
			justify-content: space-between;

			.left-box {
				display: flex;
				flex-direction: column;
				justify-content: flex-end;
				padding-left: 20rpx;
				padding-bottom: 22rpx;

				.null-location {
					display: flex;
					align-items: center;
				}

				.location {
					display: flex;
					align-items: center;
					font-weight: 500;

					.city {
						font-size: 28rpx;
					}

					.temperature {
						font-size: 32rpx;
					}

					.weather {
						font-size: 20rpx;
					}
				}

			}


			.right-img {
				width: 363rpx;


				image {
					width: 100%;
					height: 100%;
				}
			}

			.banner-box {
				width: 363rpx;
				height: 176rpx;
				position: relative;
				overflow: hidden;

				.banner-item {
					position: absolute;
					width: 100%;
					height: 100%;
					opacity: 0;
					transition: opacity 1s ease;
				}

				.banner-item.active {
					opacity: 1;
				}

				.banner-img {
					width: 100%;
					height: 100%;
				}
			}
		}

		.input-box {
			width: 100%;
			height: 76rpx;
			padding: 0 20rpx;
			box-sizing: border-box;
			margin-top: 20rpx;

			.input-item {
				border-radius: 20rpx;
				overflow: hidden;
				background: #FFFFFF;
				border: 2rpx solid #FE0F23;
			}

			.rightBtn {
				width: 92rpx;
				height: 52rpx;
				line-height: 52rpx;
				text-align: center;
				background: #FE0F23;
				border-radius: 8rpx;
				margin-right: 20rpx;
				color: #FFFFFF;
			}
		}

		.tab-bar {
			display: flex;
			align-items: center;
			width: 100%;
			height: 60rpx;
			overflow-x: auto;
			white-space: nowrap;
			margin: 20rpx 0;

			.tab-scroll {
				width: 100%;
				height: 100%;
				display: flex;
				align-items: center;
			}

			.tab-item {
				display: inline-block;
				padding: 0 22rpx;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;
			}

			.tab-item text {
				font-size: 28rpx;
				color: #010101;
			}

			.tab-item .active {
				font-weight: 600;
				font-size: 32rpx;
				color: #FE0F23;
			}

			.tab-border {
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 40rpx;
				height: 6rpx;
				background-color: #FE0F23;
				border-radius: 20rpx;
			}
		}

		.carousel-box {
			padding: 0 28rpx;
			margin-top: 20rpx;

			.carousel-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 110rpx;
				margin-right: 48rpx;

				image {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
				}

				text {
					width: 120rpx;
					text-align: center;
					font-size: 24rpx;
					color: #010101;
					margin-top: 8rpx;
				}
			}
		}
	}

	.content {
		width: 100%;
		position: absolute;
		top: 530rpx;
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
		z-index: 9;

		.left-item {
			width: 294rpx;
			height: 358rpx;
			background-image: url('@/static/index/jss.png');
			background-repeat: no-repeat;
			background-size: 100% 100%;

			.title {
				font-weight: 600;
				font-size: 28rpx;
				color: #5A3332;
				margin-top: 40rpx;
				margin-left: 40rpx;
			}

			.min-title {
				font-size: 28rpx;
				color: #C0C0C0;
				margin-top: 8rpx;
				margin-left: 40rpx;
			}

			.examine {
				width: 188rpx;
				height: 56rpx;
				background: linear-gradient(180deg, #F5C477 0%, #EC672E 100%);
				box-shadow: inset 0rpx 8rpx 8rpx 0rpx rgba(230, 230, 230, 0.39);
				border-radius: 1998rpx 1998rpx 1998rpx 1998rpx;
				font-weight: 600;
				font-size: 28rpx;
				color: #FFFFFF;
				text-align: center;
				line-height: 56rpx;
				margin-top: 176rpx;
				margin-left: 20rpx;
			}
		}

		.right-item {
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.item {
				width: 396rpx;
				padding-left: 40rpx;
				box-sizing: border-box;

				.min-title {
					font-size: 28rpx;
					color: #C0C0C0;
					margin-top: 8rpx;
				}
			}

			.i1 {
				height: 160rpx;
				background-image: url('@/static/index/ghs.png');
				background-repeat: no-repeat;
				background-size: 100% 100%;

				.title {
					font-weight: 600;
					font-size: 28rpx;
					color: #5A3332;
					margin-top: 40rpx;
				}
			}

			.i2 {
				height: 178rpx;
				background-image: url('@/static/index/ddyx.png');
				background-repeat: no-repeat;
				background-size: 100% 100%;

				.title {
					font-weight: 600;
					font-size: 28rpx;
					color: #294B50;
					margin-top: 40rpx;
				}
			}
		}
	}

	.hotGoods {
		box-sizing: border-box;
		position: relative;
		top: 920rpx;
		background-color: #F7F7F7;
		z-index: 9;

		.top-title-img {
			display: flex;
			align-items: center;
			padding-left: 20rpx;
			margin-bottom: 20rpx;

			.img1 {
				width: 80rpx;
				height: 80rpx;
			}

			.img2 {
				width: 190rpx;
				height: 32rpx;
				margin-left: 22rpx;
			}
		}

		.header-hotGoods {
			display: flex;
			width: 100%;
			// background: url("@/static/static-home/image52.png") no-repeat;
			// background-size: 100% 100%;
			padding: 0 40rpx;
			box-sizing: border-box;


			.left {
				font-weight: 400;
				font-size: 32rpx;
				color: #5B8065;
				margin-right: 40rpx;
				margin-bottom: 28rpx;


			}

			.right {
				font-weight: 400;
				font-size: 32rpx;
				color: #5B8065;
				margin-bottom: 28rpx;

			}

			.activeSelect {
				font-weight: 500;
				font-size: 32rpx;
				color: #323232;
			}
		}

		.list-content {
			padding: 20rpx;
			min-height: 600rpx;
			border-bottom-left-radius: 10rpx;
			border-bottom-right-radius: 10rpx;
			height: auto;
			box-sizing: border-box;
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			grid-row-gap: 20rpx;
			grid-column-gap: 22rpx;
			padding-top: 18rpx;
			background: #F6F6FA;
		}
	}
</style>